
#if	!defined( __20080830_DEF_WIN_DIRITERATOR_H__ )
#define	__20080830_DEF_WIN_DIRITERATOR_H__

#if	defined( PCE_CFG_OS_Windows )

#include	<io.h>
#include	<errno.h>
#include	<string>

namespace PCE_Lib {
namespace CEnv_Def {
namespace PCE_Lib_CurrentCEnvironment {
namespace Tools {

class DirIterator
{
public:
	class DirEntry
	{
	public:
		void Clear( void ) throw() { m_Path.clear(); m_Name.clear(); }
	public:
		DirEntry( void ) throw() : m_Path(), m_Name() {}
	public:
		::std::string	m_Path;
		::std::string	m_Name;
	};
public:
	const DirEntry * Read( void ) throw()
	{
		if( m_Finished ) {
			return Null< const DirEntry * >();
		}
		if( ! m_FirstFile ) {
			if( 0 != _findnext( m_Handle, & m_FileInfo ) ) {
				m_Finished = true;
				return Null< const DirEntry * >();
			}
		}
		m_FirstFile = false;
		m_Entry.m_Name = m_FileInfo.name;
		return & m_Entry;
	}
	bool Open( const char_t * dir )
	{
		assert( NotNull( dir ) );

		if( ! Close() ) {
			return false;
		}
		m_Entry.m_Path = dir;
		if( (m_Entry.m_Path.size() > 0) && ('/' != *(m_Entry.m_Path.end() - 1)) ) {
			m_Entry.m_Path += '/';
		}

		m_Handle = _findfirst( (m_Entry.m_Path + '*').c_str(),  & m_FileInfo );
		if( -1 == m_Handle ) {
			return ENOENT == errno;
		}
		m_Finished = false;
		return  true;
	}
	bool Close( void ) throw()
	{
		bool	ret_val = true;

		m_Entry.Clear();
		if( -1 != m_Handle ) {
			ret_val = ( 0 == _findclose( m_Handle ) );
			m_Handle = -1;
		}
		m_Finished = true;
		m_FirstFile = true;
		return ret_val;
	}
public:
	DirIterator( void ) throw() : m_Entry(), m_Handle( -1 ),
		m_FileInfo(), m_Finished( true ), m_FirstFile( true ) {}
	~DirIterator( void ) throw() { Close(); }
protected:
	DirEntry		m_Entry;
	intptr_t		m_Handle;
	_finddata_t		m_FileInfo;
	bool			m_Finished;
	bool			m_FirstFile;
};

}	// Tools
}	// PCE_Lib_CurrentCEnvironment
}	// CEnv_Def
}	// PCE_Lib

#else
	#error DirIterator_Win.h can only be used on Windows platform!
#endif	// PCE_CFG_OS_Windows

#endif	// __20080830_DEF_WIN_DIRITERATOR_H__
